require(['jquery',
         'global',
         'underscore',
         'module/util',
         'module/popup',
         'module/ajax',
         'bootstrap',
         'pixeladmin',
         'jquery-weui',
         'viewer',
         'requirejs/domready!'],
 function($, global, _, util){
	
	window.PixelAdmin.start();//初始化菜单
	
	var _dict_codes = new Array("HOMEWORK_TYPE", "SUBJECT", "GRADE", "TERM", "EDITION", "ISBN_INFORMATION_STATUS", "ISBN_ORDER_STATUS"), _dict = {}, _button = "<div class=\"panel-footer\"><div class=\"row\"><div class=\"pull-right col-xs-12 col-sm-auto\" style=\"padding:10px 30px 30px;\"><a class=\"btn btn-primary btn-labeled\" data-toggle=\"modal\" style=\"width: 100%;\" id=\"editIsbnInfor\"><span class=\"btn-label icon glyphicon glyphicon-edit\"></span>修改ISBN信息</a></div></div></div>";
	
	// for 转化
	var _hiddenDiv = $("#hiddenDiv");
	var _imgPreURL = $("#pagePreURL").val();
	
	var initWebsite = function() {
		
		// 未加载
		if ($("#mainView").find(".panel-body").length <= 0) {
			getInforNum();
		}
	}
	
	var getInforNum = function() {
		// 获取Information num
		$.ajax({
			url : global.context + '/web/isbninformation/getIsbnInformation',
			data : {
				barcode : $("#barcode").val()
			},
			type : 'POST',
			beforeSend : function() {
				$(".weui-infinite-scroll").show();
			},
			success : function(result) {
				debugger;
				var data = JSON.parse(result).data;
				
				for (var i = 0; i< data.length; i++) {
					$("#mainView").append("<div class=\"part-of-page\" information-id="+data[i].id+"></div>");
				}
				
				$.each($(".part-of-page"), function(){
					var informationDiv = $(this);
					var _informationId = informationDiv.attr("information-id");
					
					// load information
					loadInformation(_informationId, informationDiv);
					
					// load order
					loadOrder(_informationId, informationDiv);
					
					// load page
					loadPage(_informationId, informationDiv);
					
					// 加入按钮
					informationDiv.append(_hiddenDiv.html(_button).find(".panel-footer"));
					_hiddenDiv.empty();
					
				});
				
			},
			error : function(e) {
				$.alert("页面初始化失败！");
			},
			complete : function() {
				
				// 页面加载完成后 加载数据
				$.each($(".information-vm"), function(){
					var _informationId = $(this).parent().attr("information-id");
					
					fillInformationData(_informationId, $(this), _imgPreURL);
				});
				$.each($(".order-vm"), function(){
					var _informationId = $(this).parent().attr("information-id");
					
					fillOrderData(_informationId, $(this));
				});
				$.each($(".page-vm"), function(){
					var _informationId = $(this).parent().attr("information-id");
					
					fillPageData(_informationId, $(this), _imgPreURL);
				});
				
				// if done
				// 加载完毕
				$(".weui-infinite-scroll").hide();
			}
		});
	}
	
//  --------------------------------------------------  加载页面 -----------------------------------------------------
	var loadInformation = function(data, position) {
		$.ajax({
			url : global.context + '/web/isbninformation/getInformationView',
			data : {
				isbnInformationId : data
			},
			type : 'POST',
			async: false,
			success : function(result) {
				// 写入页面
				var writeToPage = _hiddenDiv.html(result).find(".information-vm");
				
				if (writeToPage) {
					
					position.append(writeToPage);
					_hiddenDiv.empty();
				}
			},
			error : function(e) {
				$.alert("作业本查询失败！");
			}
		});
	}
	var loadOrder = function(data, position) {
		$.ajax({
			url : global.context + '/web/isbnorder/getOrderView',
			data : {
				isbnInformationId : data
			},
			type : 'POST',
			async: false,
			success : function(result) {
				// 写入页面
				var writeToPage = _hiddenDiv.html(result).find(".order-vm");
				
				if (writeToPage) {
					
					position.append(writeToPage);
					_hiddenDiv.empty();
				}
			},
			error : function(e) {
				$.alert("订单查询失败！");
			}
		});
	}
	var loadPage = function(data, position) {
		$.ajax({
			url : global.context + '/web/isbnpage/getPagesView',
			data : {
				isbnInformationId : data
			},
			type : 'POST',
			async: false,
			success : function(result) {
				// 写入页面
				var writeToPage = _hiddenDiv.html(result).find(".page-vm");
				
				if (writeToPage) {
					
					position.append(writeToPage);
					_hiddenDiv.empty();
				}
				
			},
			error : function(e) {
				$.alert("作业本内图片查询失败！");
			}
		});
	}
	
//  --------------------------------------------------  加载页面数据 -----------------------------------------------------
	var fillPageData = function(data, position, imgPrefix) {
		$.ajax({
			url : global.context + '/web/isbnpage/getPagesData',
			data : {
				isbnInformationId : data
			},
			type : 'POST',
			success : function(result) {
				
				if (result) {
					var _returnData = JSON.parse(result).data;
					
					if (_returnData.length > 0) {
						for (var i = 0; i < _returnData.length; i++) {
							position.find("ul.images").append("<li class=\"col-sm-2\"><img class=\"img-thumbnail\" src=\""+(imgPrefix+_returnData[i].pageImageUrl)+"\" width='150' height='180' /></li>");
						}
					} else {
						position.append("<div style='text-align:center;color:red;'><label class=\"control-label\">暂无上传作业本图片</label></div>");
					}
					
				}
				
			},
			error : function(e) {
				$.alert("数据查询失败！");
			},
			complete : function() {
				// 刷新控件
				position.find('.images').viewer('update');
			}
		});
	}
	var fillOrderData = function(data, position) {
		$.ajax({
			url : global.context + '/web/isbnorder/getOrderData',
			data : {
				isbnInformationId : data
			},
			type : 'POST',
			success : function(result) {
				
				if (result) {
					var _returnData = JSON.parse(result).data;
					
					util.fillInput(position, _returnData);
				}
			},
			error : function(e) {
				$.alert("数据查询失败！");
			}
		});
	}
	var fillInformationData = function(data, position, imgPrefix) {
		$.ajax({
			url : global.context + '/web/isbninformation/getInformationData',
			data : {
				isbnInformationId : data
			},
			type : 'POST',
			success : function(result) {
				
				if (result) {
					var _returnData = JSON.parse(result).data;
					
					util.fillInput(position, _returnData);
					
					var coverImg = position.find("div.col-sm-12").find("img");
					$.each(coverImg, function() {
						var serviceUrl = $(this).attr("src");
						$(this).attr("src", imgPrefix + serviceUrl);
					})
				}
				
			},
			error : function(e) {
				$.alert("数据查询失败！");
			}
		});
	}

	var initSelect = function(place, name, dictName, optionsPre) {// 加载下拉框
		var dict = _dict[dictName];
		var options = '<option value="">'+optionsPre+'</option>';;
		for(var i in dict) {
			options += '<option value="'+i+'">'+dict[i]+'</option>';
		}
		
		if (place) {
			$.each($(place).find(name), function() {
				$(this).html(options);
			})
		} else {
			$(name).html(options);
		}
	}
	
	// 初始化数据字典
	var initDict = function() {
		$.ajax({
	        url : global.context + '/web/dictdata/findByCodes',
	        data : {codes : _dict_codes},
            type : 'POST',
            dataType : 'json',
	        success : function(result) {
	        	parseVarDict(result);
	        	
	        	initSelect(".information-vm", "[name='status']", "ISBN_INFORMATION_STATUS", "全部information状态");
	        	initSelect(".information-vm", "[name='type']", "HOMEWORK_TYPE", "全部类型");
	        	
	        	initSelect(null, "[name='subject']", "SUBJECT", "全部学科");
	        	initSelect(null, "[name='grade']", "GRADE", "全部年级");
	        	initSelect(null, "[name='term']", "TERM", "全部学期");
	        	initSelect(null, "[name='edition']", "EDITION", "全部版本");
	        	
	        	initSelect(".order-vm", "[name='status']", "ISBN_ORDER_STATUS", "全部订单类型");
	        },
	        error : function(e) {
	        	$.alert("基础数据加载失败");
	        }
		});
	};
	
	// 解析数据字典
	var parseVarDict = function(result) {
		if(result) {
    		for(var index in _dict_codes) {
    			var code = _dict_codes[index];
    			if(!result[code]) {
    				break ;
    			}
    			_dict[code] = {};// 初始化
    			for(var i in result[code]) {
    				var dict = result[code][i];
    				_dict[code][dict.value] = dict.name;
    			}
    		}
    	}
	}
	
	var toEdit = function(barcode, isbnInformationId) {
		
		if (isbnInformationId) {
			window.open(global.context + "/web/isbnmanage/editor?barcode=" + barcode + "&isbnInformationId=" + isbnInformationId);
		} else {
			window.open(global.context + "/web/isbnmanage/editor?barcode=" + barcode);
		}
	}
	
	// 绑定事件
	var bindEvent = function() {
		$("#content-wrapper").on('click','#editIsbnInfor',function(){
			var parent = $(this).parent().parent().parent().parent();
			var isbnInformationId = parent.attr("information-id");
			// to edit page
			toEdit($("#barcode").val(), isbnInformationId);
		});
	}
	var init  = function() {
		initDict();

		bindEvent();
	};
	
	init();
	initWebsite();// 初始化页面
})